package com.wohuijituan.whcsmerchant.fragment;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wohuijituan.whcsmerchant.R;
import com.wohuijituan.whcsmerchant.activity.LoginActivity;
import com.wohuijituan.whcsmerchant.activity.ShopDetailActivity;
import com.wohuijituan.whcsmerchant.bean.IsSuccessBean;
import com.wohuijituan.whcsmerchant.bean.ShopDetailBean;
import com.wohuijituan.whcsmerchant.callback.IsSuccessCallBack;
import com.wohuijituan.whcsmerchant.callback.ShopDetailCallBack;
import com.wohuijituan.whcsmerchant.url.ParamsKey;
import com.wohuijituan.whcsmerchant.url.Urls;
import com.wohuijituan.whcsmerchant.utils.ExtraName;
import com.wohuijituan.whcsmerchant.utils.LogUtils;
import com.wohuijituan.whcsmerchant.utils.MyKey;
import com.wohuijituan.whcsmerchant.utils.MyOkHttpUtils;
import com.wohuijituan.whcsmerchant.utils.MyRequestParams;

import okhttp3.Call;

/**
 * A simple {@link MyBaseFragment} subclass.
 */
public class SettingFragment extends MyBaseFragment implements View.OnClickListener{
    public static final String TAG = "SettingFragment";

    public SettingFragment() {
        // Required empty public constructor
    }

    private LinearLayout llShopInfo;
    private RelativeLayout llUserInfo;
    private LinearLayout llOpenTime;
    private RelativeLayout llFeedback;
    private RelativeLayout llAboutUs;
    private TextView tvShopName;
    private TextView tvUserPhone;
    private TextView tvUserExit;
    private TextView tvBusinessStatus;

    private ImageButton titleGoBack;
    private TextView titleName;
    private TextView titleAction;


    private void assignViews(View v) {
        titleGoBack = (ImageButton) v.findViewById(R.id.title_go_back);
        titleName = (TextView) v.findViewById(R.id.title_name);
        titleAction = (TextView) v.findViewById(R.id.title_tv_action);
        llShopInfo = (LinearLayout) v.findViewById(R.id.ll_shop_info);
        llUserInfo = (RelativeLayout) v.findViewById(R.id.ll_user_info);
        llOpenTime = (LinearLayout) v.findViewById(R.id.ll_open_time);
        llFeedback = (RelativeLayout) v.findViewById(R.id.ll_feedback);
        llAboutUs = (RelativeLayout) v.findViewById(R.id.ll_about_us);
        tvShopName = (TextView) v.findViewById(R.id.tv_shop_name);
        tvUserPhone = (TextView) v.findViewById(R.id.tv_user_phone);
        tvUserExit = (TextView) v.findViewById(R.id.tv_user_exit);
        tvBusinessStatus = (TextView) v.findViewById(R.id.tv_business_status);
    }



    private MyOkHttpUtils myOkHttpUtils;
    private MyRequestParams params;
    private static final int SetShopState_OK = 9437;
    private static final int ShopDetailRequest_OK = 8783;
    public static final int SHOP_SETTING = 87;
    private ShopDetailBean.DataEntity shopDetail = null;

    @Override
    public View createMyView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_setting, container, false);
        assignViews(view);
        initData();
        initView();
        initListener();
        ShopDetailRequest();
        return view;
    }

    private void initView() {
        titleName.setText("店铺设置");
    }

    private void initData() {
        myOkHttpUtils = new MyOkHttpUtils();
        params = new MyRequestParams();
    }

    private void initListener() {
        llShopInfo.setOnClickListener(this);
        llOpenTime.setOnClickListener(this);
        tvUserExit.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()){
            case R.id.ll_shop_info:
                intent.setClass(activity, ShopDetailActivity.class);
                intent.putExtra(ExtraName.SHOP_DETAIL, shopDetail);
                startActivityForResult(intent, SHOP_SETTING);
                break;
            case R.id.ll_open_time:
                shopStateDialog();
                break;
            case R.id.tv_user_exit:
                userExitDialog();
                break;
        }
    }
    /**
     * 弹窗退出
     */
    private void userExitDialog(){
        new AlertDialog.Builder(activity).setTitle("提示")
                .setMessage("是否退出当前用户?")
                .setNegativeButton("取消", null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        SharedPreferences sp = activity.getSharedPreferences(MyKey.userConfig, Activity.MODE_PRIVATE);
                        sp.edit().putString("userKey", "")
                                .commit();
                        myApplication.setUserKey("");
                        Intent intent = new Intent();
                        intent.setClass(ctx, LoginActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                    }
                }).create().show();
    }
    /**
     * 弹窗修改营业状态
     */
    private void shopStateDialog(){
        new AlertDialog.Builder(activity).setTitle("选择营业状态")
                .setSingleChoiceItems(new String[]{"开始营业", "暂停营业"}, 0,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (which == 0) {
                                    setShopStateRequest(true);
                                } else if (which == 1) {
                                    setShopStateRequest(false);
                                }
                                dialog.dismiss();
                            }
                        }).setNegativeButton("取消", null).show();
    }

    /**
     * 修改营业状态网络请求
     * @param isOpen
     */
    private void setShopStateRequest(final boolean isOpen){
        showDialog(ctx);
        String strUrl = Urls.SetShopState;
        params.clear();
        params.addStringRequest(ParamsKey.UserKey, myApplication.getUserKey());
        params.addStringRequest(ParamsKey.SetShopState_IsOpen,isOpen+"");
        myOkHttpUtils.postRequest(strUrl, params, new IsSuccessCallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                dismissDialog();
                showToast(ctx, "网络出错,请检查网络是否连接!");
                LogUtils.e(TAG, e.getMessage());
            }

            @Override
            public void onResponse(IsSuccessBean response, int id) {
                if (response.getState() == 1) {
                    showToast(ctx, response.getData().getMessage());
                    if (response.getData().isIsSuccess()) {
                        //营业状态修改成功
                        Message msg = new Message();
                        msg.what = SetShopState_OK;
                        msg.obj = isOpen;
                        handler.sendMessage(msg);
                    }
                } else {
                    showToast(ctx, response.getMsg());
                    dismissDialog();
                }
            }
        });
    }

    /**
     *获取商家详情
     */
    private void ShopDetailRequest(){
        showDialog(ctx);
        LogUtils.e(TAG,"ShopDetailRequest");
        String strUrl = Urls.ShopDetail;
        params.clear();
        params.addStringRequest(ParamsKey.UserKey, myApplication.getUserKey());
        myOkHttpUtils.postRequest(strUrl, params, new ShopDetailCallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                dismissDialog();
                showToast(ctx, "网络出错,请检查网络是否连接!");
                LogUtils.e(TAG, e.getMessage());
            }

            @Override
            public void onResponse(ShopDetailBean response, int id) {
                if (response.getState()==1){
                    Message msg = new Message();
                    msg.what = ShopDetailRequest_OK;
                    msg.obj = response;
                    handler.sendMessage(msg);
                }else {
                    showToast(ctx, response.getMsg());
                    dismissDialog();
                }
            }
        });
    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case SetShopState_OK:
                    //对营业状态进行设置
                    boolean isOpen = (boolean) msg.obj;
                    setShopState(isOpen);
                    dismissDialog();
                    break;
                case ShopDetailRequest_OK:
                    dismissDialog();
                    ShopDetailBean data = (ShopDetailBean) msg.obj;
                    shopDetail = data.getData();
                    fillView(shopDetail);
            }
        }
    };

    /**
     * 填充用户信息
     * @param shopDetail
     */
    private void fillView(ShopDetailBean.DataEntity shopDetail){
        setShopState(shopDetail.isS_IsBusiness());
        tvShopName.setText(shopDetail.getS_Name());
        tvUserPhone.setText(shopDetail.getSI_WarnedPhone());
    }
    /**
     * 设置营业状态
     */
    private void setShopState(boolean isOpen){
        if (isOpen){
            tvBusinessStatus.setText(R.string.business_open);
        }else {
            tvBusinessStatus.setText(R.string.business_close);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        LogUtils.e(TAG,"requestCode"+requestCode+"resultCode"+resultCode);
        if (requestCode==SHOP_SETTING){
            LogUtils.e(TAG,"requestCode==SHOP_SETTING");
            if (resultCode == Activity.RESULT_OK){
                ShopDetailRequest();
                LogUtils.e(TAG,"requestCode== Activity.RESULT_OK");
            }
        }
    }
}
